<?php

namespace app\common\model;

use think\Db;
use think\Exception;
use think\exception\ErrorException;
use think\Model;
use function Couchbase\defaultDecoder;


class RuleSz extends Model
{
	
	
	// 表名
	protected $name = 'rule_sz';
	
	// 自动写入时间戳字段
	protected $autoWriteTimestamp = false;
	
	// 定义时间戳字段名
	protected $createTime = false;
	protected $updateTime = false;
	protected $deleteTime = false;
	
	// 追加属性
	protected $append = [
	
	];
	
	public function goods()
	{
		return $this->belongsTo('goods', 'reward_goods_id', 'id', '', 'left')->setEagerlyType(0);
	}
	
	public function spec()
	{
		return $this->belongsTo('goodsSpec', 'reward_spec_id', 'id', '', 'left')->setEagerlyType(0);
	}
	
	/**
	 * 订单发佣金，记录销售数量
	 * @param $orderId
	 * @return bool
	 */
	public function rebate($orderId)
	{
		
		
		try {
			$order = Db::name('order')->find($orderId);
			$goods = Db::name('orderGoods')->where(['order_id' => $orderId])->find();
			$userModel = new \app\admin\model\User();
			
			$rebateStatus = Order::REBATE_NULL_REBATE;
			$shopWhere = [];
			$orderNumber = $order['number'];
			//推荐人返利
			if ($order['recommend_user_id']) {
				$promotionId = '';
				
				$recomendUser = Db::name('user')->find($order['recommend_user_id']);
				//销售佣金
				$saleCommission = 0;
				//获取设置信息(优先是单独设置的规则）
				$setting = Db::name('goodsRule')->where(['goods_id' => $goods['goods_id']])->find();
				if (!$setting) {
					$setting = Db::name('ruleSz')->find();
					$setting && $saleCommission = $setting['sale_amount'];
				} else {
					$saleCommission = $setting['sz_sale_amount'];
					if ($setting['rebate_level']) {
						$rebateLevel = array_filter(explode(',', $setting['rebate_level']));
						if (!in_array($recomendUser['level'], $rebateLevel)) {
							$saleCommission = 0;
						}
					}
				}
				$commission = $saleCommission * $orderNumber;
				
				//普通订单和拼团订单才有返利
				if ($orderNumber > 0 && in_array($order['order_type'],
						[Order::TYPE_NORMAL, Order::TYPE_GROUP]) && $recomendUser['level'] > 0) {
					
					if ($commission > 0) {
						$commissionModel = new Commission();
						$commissionRes = $commissionModel->rebate($order['recommend_user_id'], $order['user_id'],
							$orderId, $goods['goods_id'], $goods['id'], $commission, '销售奖励(深圳)');
						if (!$commissionRes) {
							throw new Exception('添加销售佣金出错');
						}
					}
					
					//代言人
					if ($recomendUser['level'] == $userModel::LEVEL_PROMOTION) {
						$promotionInfo = Db::name('promotion')
							->where(['user_id' => $order['recommend_user_id']])
							->find();
						if ($promotionInfo) {
							//加代言人的销量
							if ($orderNumber > 0) {
								$promotionRes = Db::name('promotion')->where(['id' => $promotionInfo['id']])
									->update([
										'sale_number' => $promotionInfo['sale_number'] + $orderNumber,
										'order_number' => $promotionInfo['order_number'] + 1,
										'sale_amount' => $promotionInfo['sale_amount'] + $order['amount']
									]);
								
								if (!$promotionRes) {
									throw new Exception('添加代言人销售出错');
								}
								$promotionItemRes = SaleItem::addRow($orderId, $recomendUser['id'], $orderNumber);
								if (!$promotionItemRes) {
									throw new Exception('添加代言人销量记录出错');
								}
							}
							
							$promotionId = $promotionInfo['id'];
							$shopWhere['id'] = $promotionInfo['agent_shop_id'];
						}
					} else {
						$shopWhere['user_id'] = $order['recommend_user_id'];
					}
				}
				
				if ($shopWhere) {
					$shop = Db::name('agentShop')->where($shopWhere)->find();
					if ($shop) {
						$data = [
							'shop_id' => $shop['role'] == $userModel::LEVEL_SHOP ? $shop['id'] : '',
							'warehouse_id' => $shop['role'] == $userModel::LEVEL_WAREHOUSE ? $shop['id'] : $shop['warehouse_id'],
							'center_id' => $shop['role'] == $userModel::LEVEL_CENTER ? $shop['id'] : $shop['center_id'],
							'theater_id' => $shop['role'] == $userModel::LEVEL_THEATER ? $shop['id'] : $shop['theater_id'],
						];
						
						$agentRes = Db::name('order')
							->where(['id' => $orderId])
							->update($data);
						if ($agentRes === false) {
							throw new Exception('记录订单归属出错');
						}
						
						//赠送的酒只给战区记销量
						if ($order['order_type'] == Order::TYPE_REWARD) {
							$shopIds = array_filter([$data['theater_id']]);
						} else {
							$shopIds = array_filter(array_values($data));
						}
						
						//添加销售和金额
						if ($shopIds) {
							$shopModel = new AgentShop();
							if ($orderNumber > 0) {
								foreach ($shopIds as $shopId) {
									$numRes = $shopModel->addNumber($shopId, $orderNumber, $order['amount'], 1,
										$orderId, $shop['id'], $promotionId);
									if (!$numRes) {
										throw new Exception('添加代理销售数量出错');
									}
								}
							}
						}
					}
				}
			}
			
			
			//添加商品销量
			$goodsRes = Db::name('goods')
				->where(['id' => $goods['goods_id']])
				->setInc('number_sale', $goods['number']);
			if (!$goodsRes) {
				throw new Exception('添加商品销量出错');
			}
			
			return true;
		} catch (ErrorException $e) {
			$this->error = $e->getMessage();
			return false;
		} catch (\Exception $e) {
			$this->error = $e->getMessage();
			return false;
		} catch (Exception $e) {
			$this->error = $e->getMessage();
			return false;
		}
	}
	
	/**
	 * 添加用户销售统计
	 * @param $userId 用户ID
	 * @param $number 数量
	 * @return int|true
	 * @throws Exception
	 */
	public function addUserSaleNumber($userId, $number)
	{
		$user = Db::name('user')->find($userId);
		return Db::name('user')->where(['id' => $userId])
			->update([
				'sale_number' => $user['sale_number'] + $number,
				'all_sale_number' => $user['all_sale_number'] + $number
			]);
	}
	
}
